<template>
	<view class="page">
		<view class="head">
			<!-- #ifdef APP-PLUS -->
			<view class="title">购物车</view>
			<!-- #endif -->
			<view class="edit" @click="isEdit = !isEdit">
				<text>{{isEdit?'完成':'编辑'}}</text>
			</view>
		</view>
		<!-- 购物车列表 -->
		<mescroll-body ref="mescrollRef" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption" :top="0">
			<view class="cart-list">
				<view class="list" v-for="(item,index) in goodsList" :key="index">
					<view class="check" @tap="onSel(index, item.checked)">
						<text :class="{'checked' : item.checked}" class="iconfont icon-checked"></text>
					</view>
					<view class="goods">
						<view class="thumb">
							<image :src="item.img[0]" mode=""></image>
						</view>
						<view class="item">
							<view class="title">
								<text class="two-omit">{{item.name}}</text>
							</view>
							<view class="attribute" @click="$refs['GoodsAttr'].show(3,item.goodsId,item.arr)">
								<view class="attr">
									<text>{{item.add1[0]}},{{item.add1[1]}}</text>
									<text class="more"></text>
								</view>
							</view>
							<view class="price-num">
								<view class="price">
									<text class="min">￥</text>
									<text class="max">{{item.price}}</text>
								</view>
								<view class="num">
									<!-- 数量组件 -->
									<uni-number-box :min='1' :max="100"  @change="updateNum($event,item,item.goodsId)" :value="item.num"></uni-number-box>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 购物车失效商品列表 -->
			<view class="lose-efficacy-list">
				<view class="lose-efficacy-title">
					<view class="title">
						<text>失效商品1件</text>
					</view>
					<view class="empty">
						<text>清空失效商品</text>
					</view>
				</view>
				<view class="list" v-for="(item,index) in 2" :key="index">
					<view class="tag">
						<text>失效</text>
					</view>
					<view class="goods" @click="onSkip('goods')">
						<view class="pictrue">
							<image :src="'/static/img/goods_thumb_0'+ (index+1) +'.png'" mode=""></image>
						</view>
						<view class="item">
							<view class="title">
								<text class="two-omit">薇妮(Viney)时尚包包女包牛皮单肩包女休闲百搭斜挎包韩版小方包潮(水电费枪色)</text>
							</view>
							<view class="explain">
								<text>商品已不能购买，请联系客服进行沟通</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 为你推荐 -->
			<view class="recommend-info">
				<view class="recommend-title">
					<view class="title">
						<image src="/static/wntj_title.png" mode=""></image>
					</view>
				</view>
				<view class="goods-list">
					<view class="list" v-for="(item,index) in goodsList" @click="onSkip('goods')" :key="index">
						<view class="pictrue">
							<image :src="item.img[0]" mode="heightFix"></image>
						</view>
						<view class="title-tag">
							<view class="tag">
								<text v-if="item.is_goods === 1">特价</text>
								{{item.name}}
							</view>
						</view>
						<view class="price-info">
							<view class="user-price">
								<text class="min">￥</text>
								<text class="max">{{item.price}}</text>
							</view>
							<view class="vip-price">
								<image src="/static/vip_ico.png"></image>
								<text>￥{{item.vip_price}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 结算 -->
			<view class="close-account">
				<view class="check-total">
					<view class="check" @tap="onAllSel">
						<text class="iconfont icon-check" :class="{ 'icon-checked': allSelected }"></text>
						<text class="all">全选</text>
					</view>
					<view class="total">
						<text>合计：</text>
						<text class="price">￥{{totalCount.totalPrice}}</text>
					</view>
				</view>
				<view class="account">
					<view class="btn-calculate" @tap="onPay" :class="{'btn-calculate1' : !isSel}" v-if="!isEdit">
						<text>去结算({{totalCount.totalNum}})</text>
					</view>
					<view class="btn-del" v-else>
						<text class="attention">移入关注</text>
						<text class="del" @tap="goodsDelete">删除</text>
					</view>
				</view>
			</view>
		</mescroll-body>
		<!-- tabbar -->
		<TabBar :tabBarShow="3"></TabBar>
		<!-- 属性规格 -->
		<goods-attr ref="GoodsAttr" @updateCartsGoods="reqCartsGoods"></goods-attr>
	</view>
</template>

<script>
	import TabBar from '../../components/TabBar/TabBar.vue';
	// 引入mescroll-mixins.js
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	import GoodsAttr from '../../components/GoodsAttr/GoodsAttr.vue';//属性规格
	import uniNumberBox from '@/components/uni-number-box/uni-number-box.vue';//增加/减少
	// 引入Vuex
	import { mapMutations, mapState, mapGetters } from 'vuex'
	export default {
		mixins: [MescrollMixin], // 使用mixin
		components: {
			TabBar,
			GoodsAttr,//属性规格
			uniNumberBox
		},
		data() {
			return {
				goodsList: [],//购物车商品数据
				allSelected:false,
				mescroll: null, // mescroll实例对象 (此行可删,mixins已默认)
				// 下拉刷新的配置(可选, 绝大部分情况无需配置)
				downOption: {},
				// 上拉加载的配置(可选, 绝大部分情况无需配置)
				upOption: {
					use: false,
					toTop: {
						src: '',
					}
				},
				isEdit: false,
			};
		},
		onReady() {
			uni.hideTabBar()
		},
		onShow(){
			this.reqCartsGoods()
		},
		methods: {
			// 0.延展mutations中的方法
			...mapMutations(['MODIFY_OBJ','DETAIL_OBJ']),
			/**
			 * 获取购物车数据
			 */
			reqCartsGoods() {
				this.$api.getCartsGoods({
					noncestr: Date.now()
				}).then((res) => {
					console.log(res)
					//处理数组
					res.data.forEach(item =>{
						for(let key in item){
							if(key === 'arr' || key === 'img'){
								item[key] = JSON.parse(item[key])
							}
						}
					})
					let add1 
					this.$cartmodel.getCartData(res=>{
						add1 = res.map(item=>{
							return item.arr.map(item1=>{
								return item1.SizeList
							})
						})
					})
					// console.log(add1)
					res.data.forEach((item,index) =>{
						item.add1 = item.arr.map((item1,index1)=>{
							return add1[index][index1][item1]

						})
						item.checked = true;
					})
					this.goodsList = res.data;
					console.log(this.goodsList)
					this.checkCartList()//全选检测
					
				}).catch((err) => {
					console.log('request fail', err);
				})
			},
			//更新商品数量
			updateNum(event, obj1, goodsId){
				if(obj1.num === event || event == 0) return false; 
				obj1.num = event;
				this.DETAIL_OBJ({obj1})
				this.$refs['GoodsAttr'].updateConfirm();
				//修改缓存
				this.$cartmodel.getCartData(res=>{
					res.forEach((item,index) =>{
						if(item.goodsId == goodsId){
							res[index].num = event;
						}
					})
					//更新缓存
					uni.setStorageSync('uni_cart', res);
				})
			},
			// 单选
			onSel(index, flag) {
				this.goodsList[index].checked = !flag;
				this.checkCartList()
			},
			// 全选
			onAllSel() {
				this.allSelected = !this.allSelected;
				this.goodsList.map(item => {
					item.checked = this.allSelected;
				})
			},
			// 全选检测
			checkCartList() {
				let all = true;
				this.goodsList.map(item => {
					if (!item.checked) {
						all = false
					}
				})
				this.allSelected = all;
			},
			// 删除
			goodsDelete() {
				console.log('进入')
				let that = this
				uni.showModal({
				    title: '提示',
				    content: '是否删除选中的商品?',
				    success: function (res) {
				        if (res.confirm) {
				            let { goodsList } = that;
							console.log(goodsList)
				            let selectedIdsArray = [];
				            for (let i = 0; i < goodsList.length; i++) {
				            	if (goodsList[i].checked) {
				            		selectedIdsArray.push(goodsList[i].goodsId);
				            		goodsList.splice(i, 1);
				            		i -= 1;
				            	}
				            }
				            //删除缓存购物车数据
				            that.$cartmodel.delete(selectedIdsArray,res=>{
				            	console.log(res)
				            })
				            
				            that.$api.deleteGoodsToCart({
				            	data:selectedIdsArray
				            }).then((res) => {
				            	console.log(res)
				            	that.checkCartList()//全选检测
				            	
				            }).catch((err) => {
				            	console.log('request fail', err);
				            })
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});

			},
			// 结算
			onPay() {
				let { goodsList } = this;
				let confirmcartList = [];
				if (this.isSel) {
					goodsList.forEach(item => {
						if (item.checked) {
							confirmcartList.push(item)
							uni.navigateTo({
								url: '/pages/ConfirmOrder/ConfirmOrder?confirmcartList=' +  JSON.stringify(confirmcartList)
							});
						}
					})
				}else{
					uni.showToast({
						title: '请选择购买的商品',
						duration: 2000,
						icon:'none'
					});
				}
			},
			/*下拉刷新的回调, 有三种处理方式:*/
			downCallback() {
				this.mescroll.endSuccess();
			},
			/*上拉加载的回调*/
			upCallback(page) {
				setTimeout(() => {
					this.mescroll.endByPage(10, 20);
				}, 2000)
			},
			/**
			 * 跳转点击
			 * @param {String} type 跳转类型
			 */
			onSkip(type) {
				switch (type) {
					case 'classify':
						uni.navigateTo({
							url: '/pages/SearchGoodsList/SearchGoodsList',
						})
						break;
					case 'goods':
						uni.navigateTo({
							url: '/pages/GoodsDetails/GoodsDetails',
							animationType: 'zoom-fade-out',
							animationDuration: 200
						})
						break;
				}
			}
		},
		computed: {
			// 购物车数量和总价
			totalCount(){
				let totalNum = 0;
				let totalPrice = 0;
				this.goodsList.filter(item => {
					if (item.checked) {
						totalNum += 1;
						totalPrice += item.num * item.price;
					}
				})
				return {
					totalNum,
					totalPrice
				}
			},
			// 是否选择了商品
			isSel(){
				let isSel = false;
				this.goodsList.map(item => {
					if (item.checked) {
						isSel = true
					}
				})
				return isSel
			},
		},
	}
</script>

<style scoped lang="scss">
	@import 'cart.scss';
</style>
